from PyPDF2 import PdfReader, PdfWriter
import os
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor

def extract_pdf_pages(input_path, output_path, start_page, end_page):
    """单文件提取函数（含进度条）"""
    try:
        reader = PdfReader(input_path)
        writer = PdfWriter()

        for page_num in range(start_page-1, end_page):
            writer.add_page(reader.pages[page_num])

        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, "wb") as f:
            writer.write(f)
        return True, f"成功：{input_path}"
    except Exception as e:
        return False, f"{input_path}失败：{str(e)}"

def batch_extract(file_tasks):
    """
    多文件批量处理器

    参数：
    - file_tasks: 元组列表，格式为[(输入路径, 输出路径, 起始页, 结束页), ...]
    """
    results = []
    with ThreadPoolExecutor(max_workers=4) as executor:
        futures = []
        for task in file_tasks:
            futures.append(executor.submit(extract_pdf_pages, *task))

        # 进度条监控
        for future in tqdm(
            futures,
            total=len(file_tasks),
            desc="批量处理进度",
            unit="文件",
            ncols=80,
            bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt}"
        ):
            results.append(future.result())

    # 打印汇总结果
    print("\n=== 处理结果 ===")
    for success, msg in results:
        status = "✅" if success else "❌"
        print(f"{status} {msg}")

# 使用示例
if __name__ == "__main__":
    tasks = [
        ("book1.pdf", "output/unit1.pdf", 1, 5),
        ("book1.pdf", "output/unit2.pdf", 6, 10),
        ("book2.pdf", "output/chapter1.pdf", 3, 7),
    ]
    batch_extract(tasks)
